﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace BestTrader.Cms.WebApi.Common
{
    public static class SwaggerExtensions
    {
        /// <summary>
        /// InitSwagger
        /// </summary>
        /// <param name="services"></param>
        public static void InitSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.OperationFilter<SwaggerFileUploadFilter>();//增加文件过滤处理
              
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;// 获取到应用程序的根路径
                //var basePath = Path.GetDirectoryName(AppContext.BaseDirectory);//get application located directory
                var xmlApiPath = Path.Combine(basePath, "BestTrader.Cms.WebApi.xml");//api文件xml(在以上步骤2设置生成xml的路径)
                var xmlModelPath = Path.Combine(basePath, "BestTrader.Cms.ViewModels.xml");//请求modelxml
                c.IncludeXmlComments(xmlApiPath, true);
                c.IncludeXmlComments(xmlModelPath, true);
                c.SwaggerDoc("v1", new Info
                {
                    Title = "BestTrader 数据接口",
                    Version = "v1",
                    Description = "这是一个webapi接口文档说明",
                    TermsOfService = "None",
                    Contact = new Contact
                    {
                        Name = "Tang Gao",
                        Email = "qq23745038@126.com",
                        Url = "http://localhost:63850"
                    },
                    License = new License
                    {
                        Name = "Swagger官网",
                        Url = "http://swagger.io/",
                    }
                });

                //Show the api version in url address
                c.DocInclusionPredicate((version, apiDescription) =>
                {
                    var values = apiDescription.RelativePath
                        .Split('/')
                        .Select(v => v.Replace("v{version}", version));

                    apiDescription.RelativePath = string.Join("/", values);

                    return true;
                });

                c.IgnoreObsoleteActions();

                var security = new Dictionary<string, IEnumerable<string>>
                {
                    {"Bearer", new string[] { }},
                };

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                c.AddSecurityRequirement(security);

            });

        }

        /// <summary>
        /// ConfigureSwagger
        /// </summary>
        /// <param name="app"></param>
        public static void ConfigureSwagger(this IApplicationBuilder app)
        {
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "docs/{documentName}/swagger.json"; // 使中间件服务生成Swagger作为JSON端点(此处设置是生成接口文档信息，可以理解为老技术中的webservice的soap协议的信息，暴露出接口信息的地方)
                c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Info.Description = httpReq.Path);// 请求过滤处理
            });
            app.UseSwaggerUI(s =>
            {
                s.RoutePrefix = "swagger";
                s.SwaggerEndpoint("/swagger/v1/swagger.json", "BestTrader WebApi V1");
                s.IndexStream = () => typeof(SwaggerExtensions).GetTypeInfo().Assembly.GetManifestResourceStream("BestTrader.Cms.WebApi.index.html");
            });

        }
    }
}